<?php

/**
 * 省市区
 */

namespace app\api\model;

use PDOStatement;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\Model;
use think\Db;

class Region extends Model {

    /**
     * 筛选条件的区域列表    区域-商圈关系
     * @param $map
     * @param $column
     * @return array|PDOStatement|string|Collection
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    static function get_list($map) {
        $column = ['name', 'city_code', 'id'];
        //区域
        $per = db::name('region')->where('p_code', $map)->order('weights asc')->field($column)->select();
        $ids = array_column($per, 'city_code');
        //区域下面所有商圈
        $business_area = db::name('business_area')->where('city_id', 'in', $ids)->field('name,city_id,id')->select();
        $per = array_column($per, null, 'city_code');

        foreach ($business_area as $val) {
            if (isset($per[$val['city_id']])) {
                $per[$val['city_id']]['children'][] = $val;
            }
        }
        $per = array_values($per);
        for ($i2 = 0; $i2 < count($per); $i2++) {
            $str = 'c-' . $per[$i2]['city_code'];
            if (!empty($per[$i2]['children'])) {
                array_unshift($per[$i2]['children'], ['name' => '不限', 'city_id' => $per[$i2]['city_code'], 'id' => $str]);
            } else {
                $per[$i2]['children'] = [['name' => '不限', "city_id" => $per[$i2]['id'], "id" => $str]];
            }
        }
        array_unshift($per, [
            'name' => '不限',
            'city_code' => intval($map),
            'id' => 0,
            'children' => [['name' => '不限', "city_id" => intval($map), "id" => 0]]
        ]);
        return $per;
    }

    /**
     * 首页地址
     * @param $params
     * @return array|PDOStatement|string|Collection
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    static public function CityHome($params) {
        $map = [];
        if (!empty($params['city_name'])) {
            $params['city_name'] = strtoupper($params['city_name']);
            $map[] = ['name|initials', 'like', '%' . trim($params['city_name']) . '%'];
        }
        $map[] = ['rank', '=', 2];
        $column = ['name', 'city_code', 'initials', 'x(location) as lng', 'Y(location) as lat'];
        $data = db::name('region')
            ->where($map)
            ->field($column)
            ->order('initials', 'asc')
            ->select();
        foreach ($data as $k => $v) {
            $data[$k]['lng'] = (string)$v['lng'];
            $data[$k]['lat'] = (string)$v['lat'];
        }
        return $data;
    }

    /**
     * 首页城市列表处理
     * @param $city
     * @return array
     */
//    static public function get_all_city($city) {
//        foreach ($city as $k => $vo) {
//            $array[ $vo['initials'] ][] = $vo;
//        }
//        return array_values($array);
//    }

    /**
     * 地图找房-区域
     * @param $params
     * @return array|PDOStatement|string|Collection
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    function get_area($params) {
        //市下面的全部区域
        $region = Db::name('region')
            ->where('p_code', $params['city_code'])
            ->where('rank', 3)
            ->field('name,city_code,  x(location) as lng,Y(location) as lat,house_number as house_num')
            ->select();

        foreach ($region as $k => $v){
            if (!$v['lng']||!$v['lat']){
                unset($region[$k]);
            }
        }
        return array_values($region);
    }

    /**
     * 购房需求提供的区域数据
     * @param $params
     * @return array|PDOStatement|string|Collection
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function get_area_list($params) {
        return Db::name("region")->where("p_code", $params['city_code'])->order('weights asc')->field('name,city_code')->select();
    }

    /**
     * 根据城市code找下面的区域
     */
    public static function getCity_area($city_code, $column) {
        return Db::name("region")->where('p_code', $city_code)->field($column)->select();
    }

    /**
     * 根据区域code找上级城市
     * @param $area_code
     * @return array|PDOStatement|string|Collection
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getUp_city($area_code) {
        $down = Db::name("region")->where('city_code', $area_code)->field('p_code,name')->find();
        $up = Db::name("region")->where('city_code', $down['p_code'])->field('name')->find();
        return ['area_name' => $down['name'], 'city_name' => $up['name']];
    }

    /**
     * 区域code转城市code
     * @param $code
     * @return mixed
     */
    public static function areaTocity($code) {
        $p_codes = db('region')->where('city_code', $code)->value('p_codes');
        $p_codes = explode(',', $p_codes);
        return $p_codes[2];
    }

    /**
     * 定位公司所属城市数据
     * @param $headers
     * @return mixed
     */
    public function getCityHome($com){
//        halt($com);
        $data=db('company')->field('city_code,default_city_code')->where("id={$com['company_id']} and deleted=0")->find();
        $def_city=$data['default_city_code']?explode('-',$data['default_city_code']):[];
        if ($com['company_shop_id']){
            $shop_city=db('company_shop')->where("id={$com['company_shop_id']} and deleted=0")->value('city_code');
            $def_city=$shop_city?explode('-',$shop_city):[];
        }
        $region=db('region')->field('x(location) as lng,Y(location) as lat')->where("city_code={$def_city[0]}")->find();
        $def_city=['code'=>$def_city[0],'name'=>$def_city[1],'lng'=>$region['lng'],'lat'=>$region['lat']];
        $all_city=$data['city_code']?explode(',',$data['city_code']):[];
        $re=[];
        foreach ($all_city as $key =>$value){
            if ($value){
                $arr=explode('-',$value);
                $re[]=$arr[0];
            }

        }
        $home_city=db('region')->field('x(location) as lng,Y(location) as lat,name,city_code')->where("city_code",'in',$re)->select();
        $info['def_city']=$def_city;
        $info['home_city']=$home_city;

        return $info;
    }
}
